package cn.virens.web.components.open.wxma.router;

import java.io.Serializable;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import cn.virens.web.components.open.session.WxSessionManager;
import cn.virens.web.components.open.wxma.session.WxMaSessionMessage;

public class WxMaRouterRuleWarp implements Serializable {
	private static final long serialVersionUID = -3526597272052208142L;

	private final WxMaRouterRuleHandler handler;

	private int order = 0;
	private String msgType;
	private String fromUser;

	private String event;

	private String content;
	private String contentRegex;

	private boolean async = true;
	private boolean reEnter = false;

	public WxMaRouterRuleWarp(WxMaRouterRuleHandler handler) {
		this.handler = handler;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}

	public void setFromUser(String fromUser) {
		this.fromUser = fromUser;
	}

	public void setEvent(String event) {
		this.event = event;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setContentRegex(String contentRegex) {
		this.contentRegex = contentRegex;
	}

	public boolean isAsync() {
		return async;
	}

	public void setAsync(boolean async) {
		this.async = async;
	}

	public boolean isReEnter() {
		return reEnter;
	}

	public void setReEnter(boolean reEnter) {
		this.reEnter = reEnter;
	}

	protected boolean test(WxMaSessionMessage wxMessage) {
		if (use(event) && !matche1(event, wxMessage.getEvent())) return false;
		if (use(msgType) && !matche1(msgType, wxMessage.getMsgType())) return false;
		if (use(content) && !matche0(content, wxMessage.getContent())) return false;
		if (use(fromUser) && !matche1(fromUser, wxMessage.getFromUser())) return false;

		if (use(contentRegex) && !matche2(contentRegex, wxMessage.getContent())) return false;

		return true;
	}

	protected String handle(WxMaSessionMessage wxMessage, WxSessionManager sessionManager) {
		return handler.handle(wxMessage, sessionManager);
	}

	protected int compare(WxMaRouterRuleWarp b) {
		return Integer.compare(order, b.order);
	}

	private static boolean use(String text) {
		return text != null && !text.isEmpty();
	}

	private static boolean matche0(String text, String value) {
		return value != null && text.equals(value);
	}

	private static boolean matche1(String text, String value) {
		return value != null && text.equalsIgnoreCase(value);
	}

	private static boolean matche2(String text, String value) {
		return Pattern.matches(text, StringUtils.trimToEmpty(value));
	}

	@Override
	public String toString() {
		return "路由规则：" + handler.getClass().getSimpleName() + "." + order;
	}
}
